const userSchema = require('../../db/schema/user');
const jwtObj = require('../../common/jwt');
const bcryptPwd = require('../../common/bcryptPwd');

/*
*  用户模型相关的数据库操作逻辑
* */

const userCtrl = {
  // 用户登录
  async login(ctx) {
    try {
      // 从ctx请求上下文中取出用户名、密码
      const {userName, password} = ctx.request.body;
      // 从数据库中查询改用户名第二个参数且值为0代表不返回该字段
      const userData = await userSchema.findOne({userName}, {_id: 0, __v: 0});
      if (!userData) {
        ctx.body = {code: -1, msg: '用户不存在'};
        return
      }

      const vaildPwd = bcryptPwd.comparePwd(password, userData.password);

      switch (vaildPwd) {
        case false:
          ctx.body = {code: -1, msg: '密码错误'};
          break;
        case true:
          const token = jwtObj.createToken({userName, _id: userData._id});
          ctx.body = {
            message: '登陆成功',
            code: 0,
            data: {
              createTime: userData.createTime,
              userName: userData.userName,
              gender: userData.gender,
              avatar: userData.avatar,
              birthday: userData.birthday,
              token: token
            }
          };
          break;
        default :
          ctx.body = {code: -1, msg: '登录出错'};
      }

    } catch (e) {
      ctx.body = {
        code: -1,
        msg: e.message || '系统错误'
      };
    }


  },

  async register(ctx) {
    try {
      const reqBody = ctx.request.body;
      const hasUser = await userSchema.findOne({userName: reqBody.userName});
      if (!!hasUser) {
        ctx.body = {code: -1, msg: '用户名已存在'};
        return
      }
      // 加密密码
      reqBody.password = bcryptPwd.encrypt(reqBody.password);
      // 写入数据库
      const data = await new userSchema(reqBody).save();
      ctx.body = {
        code: 0,
        data: {
          userName: reqBody.userName
        },
        msg: '注册成功'
      }
    } catch (e) {
      ctx.body = {
        code: -1,
        msg: e.message || '系统错误'
      };
    }

  }
};

module.exports = userCtrl;
